Qt qml TextField TextInput等文本输入控件中validator属性的设置 | 您所在的位置:网站首页 › qt 只能输入数字 › Qt qml TextField TextInput等文本输入控件中validator属性的设置 |
一 环境 桌面系统: Ubuntu16.04 32位 Qt版本:5.5.1
二 限制输入框只输入数字(通过设置 validator) 1 IntValidator 作用:限制输入的内容为整数,通过bottom和top值来设置输入范围; 例子: (直接贴qt官网的例子) TextInput{ validator: IntValidator{bottom: 11; top: 31;} focus: true } 解读:限制该输入框只可以输入11~31之间的整数
2 DoubleValidator 作用:限制输入的内容为浮点数,通过bottom和top 来设置输入范围, 通过decimals 来设置小数位个数; TextInput{ validator: DoubleValidator{id:rdecimal; decimals: 2; bottom: 1.00; top: 20.00 ;notation:DoubleValidator.StandardNotation} focus: true } 解读:限制小数位位数为2位,输入值范围 1.00~20.00 ,使用标准表示法,(根据需要还可设置成科学表示法) 缺点:输入范围外的值也能正常输入,只是无效而已, 所以对于只输入数字建议使用 SpinBox 控件 二 RegExpValidator 1作用:使用正则表达式来验证输入 ,功能强大,但比较复杂; 2简单例子 TextInput{ validator: RegExpValidator { regExp: /^\d+(\.\d{0,3})?$/ } focus: true } 解读:以数字开头,数量不限,小数位位数0~3,小数位可有可无 ;
3动态正表达式 实现方法:使用构造函数 Row{ spacing: 5 TextField{ id:tfdata text: "0" validator: RegExpValidator{id:regexp ; regExp: /^\d+(\.\d{0,1})?$/ } } TextField{ id:tfdecimal text: "0" validator: IntValidator{ bottom: 0;top:20} //限制整型值 0~20 } Button{ id:bsetdecimal text: qsTr("confirme") onClicked: { var reg = new RegExp("^\\d+(\\.\\d{0,"+ tfdecimal.text + "})?$") //注意:对于\需要用\\表示 regexp.regExp = reg } } }操作:在tfdecimal输入框中输入3,然后点击 按钮即可将 tfdata输入框的小数位从原来的1位变成了3位;重点在Button 中 onClicked事件的处理;
|
CopyRight 2018-2019 实验室设备网 版权所有 |